import {parse} from 'querystring';
import pathRegexp from 'path-to-regexp';
import {Route} from '@/models/connect';
import {get, cloneDeep} from "lodash"
import {CarryOutOutlined} from "@ant-design/icons/lib";
import React from "react";
import {ReactNode} from "react";
import {SelectOptionItem} from "@/pages/Public/Public.interface";
import {message} from "antd";
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = (path: string): boolean => reg.test(path);
export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};
// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const {NODE_ENV} = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};
export const getPageQuery = () => parse(window.location.href.split('?')[1]);
/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */
export const getAuthorityFromRouter = <T extends Route>(
  router: T[] = [],
  pathname: string,
): T | undefined => {
  const authority = router.find(
    ({routes, path = '/', target = '_self'}) =>
      (path && target !== '_blank' && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname)),
  );
  if (authority) return authority;
  return undefined;
};
export const getRouteAuthority = (path: string, routeData: Route[]) => {
  let authorities: string[] | string | undefined;
  routeData.forEach((route) => {
    // match prefix
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority;
      }
      // exact match
      if (route.path === path) {
        authorities = route.authority || authorities;
      }
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};
export const getParams = (params: any) => {
  let str = '';
  let index = 0;
  if (params) {
    for (const i in params) {
      index++;
      if (index == 1) {
        str += `?${i}=${params[i]}`;
      } else {
        str += `&${i}=${params[i]}`;
      }
    }
  }
  return str;
};
export const checkCode = (params: any): Boolean => {
  if (params <= 300 || params >= 200) {
    return true
  }
  return false
};
/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 * @param {*} label el-tree 默认 'label'
 */
export function handleTree(data?: any, id?: string, parentId?: string, children?: any, rootId?: string, label?: string) {
  let conver = (res: any) => {
    res.title = res.deptName
    res.key = res.id
    //res.icon = `<CarryOutOutlined/>`
    return res
  }
  id = id || 'id'
  parentId = parentId || 'parentId'
  children = children || 'children'
  rootId = rootId || "0"
  label = label || 'label'
  //对源数据深度克隆
  const cloneData = cloneDeep(data)
  //循环所有项
  const treeData = cloneData.filter(father => {
    if (!father['label']) {
      father['label'] = father[label]
      conver(father)
    }
    let branchArr = cloneData.filter(child => {
      if (!child['label']) {
        child['label'] = child[label]
        conver(child)
      }
      //返回每一项的子级数组
      return father[id] === child[parentId]
    });
    branchArr.length > 0 ? father.children = branchArr : '';
    //返回第一层
    return father[parentId] == rootId;
  });
  return treeData != '' ? treeData : data;
}
interface GetParentDeptKeys {
  key1: string
  key2: string
}
//获取祖籍  生成导航栏
//如果是获取部门
//key1 : id
//key2 : deptName
export const getParentDept = (id: any, data: [], {key1, key2}: GetParentDeptKeys) => {
  var arr = [];
  for (var i = 0; i < data.length; i++) {
    arr.push({
      id: get(data[i], key1, ""),
      name: get(data[i], key2, "")
    });
  }
  return arr
}
export const updateState = (context: any, name: string, attrKey: string, attrVal: any, callback: (res: any) => {}) => {
  let target = context.state[name]
  target[attrKey] = attrVal
  context.setState({
    [target]: target
  }, (res: any) => {
    callback(context.state[name])
  })
}
export const currentValue = (context: any, res: any, name: string, callback: (res: any) => {}) => {
  let options = context['state'][name]['options']
  let selected = options.filter((item: any) => {
    return item.key == res.key
  })[0]
  context.setState({
    [name]: {
      options,
      currentValue: selected
    }
  }, () => {
    callback(context['state'][name])
  })
}
export const initSelectOptions = ({
                                    context,
                                    propsName,
                                    isFirstEmptyOption,
                                    parentGetPropsKey,
                                    selectTypeKeyName
                                  }: {
  context: any,
  propsName: string,//父传入的currentValue
  isFirstEmptyOption: boolean,
  parentGetPropsKey: string,
  selectTypeKeyName: string
}) => {
  let props = cloneDeep(context['props'])
  let target = get(props, propsName, {})
  let dataSource: SelectOptionItem[] = target.data.map((res: any, index: number) => {
    res.key = res.dictValue
    res.label = res.dictLabel
    res.data = cloneDeep(res)
    return res
  })
  if (isFirstEmptyOption) {
    dataSource.unshift({key: "", label: ""})
  }
  context['state'][selectTypeKeyName]['options'] = dataSource
  let parentGetPropsValue = get(props, parentGetPropsKey, 0)
  if (isNaN(parentGetPropsValue) && !parentGetPropsValue) {
    context['state'][selectTypeKeyName]['currentValue'] = {key: "", label: ""}
  } else {
    context['state'][selectTypeKeyName]['currentValue'] = context['state'][selectTypeKeyName]['options'].filter((res: any) => {
      return res.key == parentGetPropsValue
    }) [0]
  }
  context.setState({
    [selectTypeKeyName]: context['state'][selectTypeKeyName]
  }, (res: any) => {
  })
}
export const checkSelectOptionsIsInit = (
  {
    context,
    propsName,
    fetchPath,
    selectTypeKeyName,
    isFirstEmptyOption,
    parentGetPropsKey
  }:
    { context: any, propsName: string, fetchPath: string, selectTypeKeyName: string, isFirstEmptyOption: boolean, parentGetPropsKey: string }
) => {
  if (context['props'][propsName]) {
    initSelectOptions({
      context,
      propsName,
      isFirstEmptyOption,
      parentGetPropsKey,
      selectTypeKeyName
    })
  } else {
    if (context['props']['dispatch']) {
      context['props']['dispatch']({
        type: fetchPath
      }).then((res: any) => {
        initSelectOptions({
          context,
          propsName,
          isFirstEmptyOption,
          parentGetPropsKey,
          selectTypeKeyName
        })
      })
    }
  }
}
export const exeRequestResult = (res: any): boolean => {
  if (get(res, "code", false)) {
    message.success('success!');
    return true
  }
  return false
}
const addZero = (number) => {
  if (number < 10) {
    number = '0' + number;
  }
  return number;
}
// 根据身份证号码获取 出生日期，年龄，性别
export const analyzeCardId = (cardId) => {

  var userInfo = {};
  if (!cardId) {
    return userInfo;
  }
  //获取性别
  if (parseInt(cardId.substr(16, 1)) % 2 == 1) {
    userInfo.sex = '1'
  } else {
    userInfo.sex = '0'
  }
  //获取出生年月日
  var yearBirth = cardId.substring(6, 10);
  var monthBirth = cardId.substring(10, 12);
  var dayBirth = cardId.substring(12, 14);
  userInfo.dateOfBirth = yearBirth + '-' + addZero(monthBirth) + '-' + dayBirth
  //获取当前年月日并计算年龄
  var myDate = new Date();
  var monthNow = myDate.getMonth() + 1;
  var dayNow = myDate.getDay();
  var age = myDate.getFullYear() - yearBirth;
  if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
    age--;
  }
  //得到年龄
  userInfo.age = age;
  //返回性别和年龄
  return userInfo;
}
